package com.walle.gatewayserver.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.walle.gatewayserver.base.CodeContant;
import com.walle.gatewayserver.service.ITokenService;
import com.walle.gatewayserver.utils.GetResponseBodyUtil;
import com.walle.gatewayserver.vo.ApiResult;
import com.walle.gatewayserver.vo.TokenInfo;
import com.walle.gatewayserver.vo.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;
@Slf4j
@Component
public class LoginFilter extends ZuulFilter {

	@Value("${login.url}")
	private String loginUrl;
	@Autowired
	private ITokenService tokenService;
	
	@Override
	public Object run() throws ZuulException {
		try {
			RequestContext ctx = RequestContext.getCurrentContext();
			HttpServletRequest request = ctx.getRequest();
			String sysType = request.getHeader("sysType");
			
			
			ApiResult apiResult = null;
			if(StringUtils.isEmpty(sysType)) {
				apiResult = new ApiResult<>(CodeContant.SYSTYPE_NULL.getCode(), CodeContant.SYSTYPE_NULL.getMsg());
				ctx.setSendZuulResponse(false);
				ctx.setResponseStatusCode(200);
				ctx.setResponseBody(JSON.toJSONString(apiResult));
				return null;
			}
			ctx.setSendZuulResponse(true);
			ctx.setResponseStatusCode(200);
			
			String body = GetResponseBodyUtil.getResponseBody(ctx);
			
			Map result =  (Map) JSON.parse(body);
			
			if(result.get("code")!=null&&result.get("code").equals(1)) {
				
				
				Map<String, Object> data = (Map<String, Object>) result.get("data");
				UserInfo user = new UserInfo();
				user.setAccount(String.valueOf(data.get("email")));
				user.setUid(String.valueOf(data.get("userId")));
				user.setName(String.valueOf(data.get("trueName")));
				TokenInfo tokenInfo = tokenService.createTokenInfo(user, sysType);
				
				
				result.put("token",tokenInfo.getTokenId());
				
				ctx.setResponseBody(JSON.toJSONString(result));
			} else {
				ctx.setResponseBody(body);
			}
			
		} catch (IOException e) {
			log.error("=====登录验证异常======",e);
		} catch (Exception e) {
			log.error("=====登录验证异常======",e);
		}
		return null;
	}

	@Override
	public boolean shouldFilter() {

		RequestContext ctx = RequestContext.getCurrentContext();
		HttpServletRequest request = ctx.getRequest();
		
		boolean flag = false;
		
		if(!StringUtils.isEmpty(loginUrl)) {
			
			String uri = request.getRequestURI();
			
			String[] strs = loginUrl.split(",");
			
			for (String str : strs) {
				
				if(str.trim().equals(uri.trim())) {
					flag =true;
					break;
				}
				
			}
			
		}
		return flag;
	}

	@Override
	public int filterOrder() {
		// TODO Auto-generated method stub
		return 2;
	}

	@Override
	public String filterType() {
		// TODO Auto-generated method stub
		return "post";
	}

}
